<template>
  <div class="top">
    <el-radio-group v-model="saleType" size="large">
      <el-radio-button label="sale_">销量</el-radio-button>
      <el-radio-button label="_money">销售额</el-radio-button>
    </el-radio-group>
    <el-select v-model="saleDay" class="m-2" placeholder="Select" size="large">
      <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
  </div>
  <div id="pie" class="pie"></div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  data: {
    type: Object,
    default: {}
  }
})
// 销量/销售额
const saleType = ref('sale_')
// 天数
const saleDay = ref('yesterday')
const options = [
  {
    label: '昨天',
    value: 'yesterday'
  }, {
    label: '今天',
    value: 'today'
  },
  {
    label: '前3天',
    value: 'three_days'
  },
  {
    label: '前7天',
    value: 'seven_days'
  }
]

type EChartsOption = echarts.EChartsOption;

interface IPieData {
  name: string;
  value: number;
}

interface IIndexState {
  pieData: IPieData[]
}

const state = reactive<IIndexState>({
  pieData: []
})

const draw = () => {
  var chartDom = document.getElementById('pie')!;
  var myChart = echarts.init(chartDom);
  var option: EChartsOption;
  const data = props.data as ISalePieModel[];
  const key = saleType.value === 'sale_' ? saleType.value + saleDay.value : saleDay.value + saleType.value;
  state.pieData = data.map(item => ({ name: item.name, value: parseFloat(item[key]) }))

  option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      right: 20,
      height: 100,
      orient: 'vertical'
    },
    series: [
      {
        type: 'pie',
        center: ['20%', '50%'],
        radius: ['40%', '70%'],
        label: {
          show: true,
          position: 'outside'
        },
        emphasis: {
          label: {
            show: true,
            // fontSize: '40',
            // fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: state.pieData
      }
    ]
  };

  option && myChart.setOption(option);
}

// 在有数据之后，再进行图表的渲染
watch(() => props.data, () => {
  const data = props.data as ISalePieModel[];
  if (data.length === 0) return;
  draw()
})

// 修改 类型 和天数
watch([() => saleType.value, () => saleDay.value], () => {
  // 修改pieData的数据
  const data = props.data as ISalePieModel[];
  // 根据选中的是 销量 还是 销售额 决定显示的数据是哪个
  // 如果是 销量 要获取的是： item.sale_天数
  // 如果是 销售额 要获取的是： item.天数_money
  // const key = newType === 'sale_' ? newType + newDay : newDay + newType;
  // state.pieData = data.map(item => ({ name: item.name, value: parseFloat(item[key]) }))
  draw()
})


</script>
 
<style lang="less" scoped>
.top {
  display: flex;
  justify-content: space-between;
}
.pie {
  width: 100%;
  height: 350px;
}
</style>